package com.xsq.util;

import java.util.ArrayList;
import java.util.List;

import android.content.SharedPreferences;

import com.alibaba.fastjson.JSON;
import com.common.utils.LogUtils;
import com.xsq.Constant;
import com.xsq.bo.ServerInfo;
import com.xsq.bo.ServerInfos;

public class ServerUtils {

	
	private SharedPreferences preferences;
	private SharedPreferences.Editor editor;
	
	public ServerUtils(SharedPreferences preferences,SharedPreferences.Editor editor){
		this.preferences = preferences;
		this.editor = editor;
	}
	
	
	
	
	public  String getAvailableServer() {
		String serverStr = preferences.getString(Constant.CACHE_SERVERINFO, "");
		if(serverStr.equals("")){
			//还没有设置服务器信息
			return null;
		}
		ServerInfos infos = JSON.parseObject(serverStr, ServerInfos.class);
		for(ServerInfo info : infos.getServers()){
			if(info.getStatus()!=null && info.getStatus().equals("1")){
				return info.getServer();
			}
		}
		return null;
	}
	
	public List<String> getAllAviableServers(){
		String serverStr = preferences.getString(Constant.CACHE_SERVERINFO, "");
		if(serverStr.equals("")){
			//还没有设置服务器信息
			return null;
		}
		List<String> list = new ArrayList<String>();
		ServerInfos infos = JSON.parseObject(serverStr, ServerInfos.class);
		for(ServerInfo info : infos.getServers()){
			if(info.getStatus()!=null && info.getStatus().equals("1")){
				list.add(info.getServer());
			}
		}
		return list;
	}
	
	public List<String> getAllServers(){
		String serverStr = preferences.getString(Constant.CACHE_SERVERINFO, "");
		if(serverStr.equals("")){
			//还没有设置服务器信息
			return null;
		}
		List<String> list = new ArrayList<String>();
		ServerInfos infos = JSON.parseObject(serverStr, ServerInfos.class);
		for(ServerInfo info : infos.getServers()){
			if(info.getStatus()!=null ){
				list.add(info.getServer());
			}
		}
		return list;
	}

	public void setServer(String server, String status) {
		if (server != null && !server.equals("") && status != null && !status.equals("")) {
			String serverStr = preferences.getString(Constant.CACHE_SERVERINFO, "");
			ServerInfos infos = null;
			if (serverStr.equals("")) {
				infos = new ServerInfos();
			} else {
				infos = JSON.parseObject(serverStr, ServerInfos.class);

			}
			infos.updateServer(server, status);
			LogUtils.info("--->"+JSON.toJSONString(infos));
			editor.putString(Constant.CACHE_SERVERINFO, JSON.toJSONString(infos));
			editor.commit();
		}

	}
	
	public void removeAllServer(){
		String serverStr = preferences.getString(Constant.CACHE_SERVERINFO, "");
		ServerInfos infos = null;
		if (serverStr.equals("")) {
			infos = new ServerInfos();
		} else {
			infos = JSON.parseObject(serverStr, ServerInfos.class);
		}
		infos.getServers().clear();
		editor.putString(Constant.CACHE_SERVERINFO, JSON.toJSONString(infos));
		editor.commit();
	}
	
}
